import asyncio
from typing import Optional
from .speed_rs import rs_async_ping  # Rust 实现的 Ping

class SpeedOptimizer:
    _CACHE = {}  # 缓存最近测速结果
    MAX_CACHE_AGE = 300  # 5分钟缓存
    
    def __init__(self):
        self.rust_enabled = True  # 自动检测 Rust 是否可用
        
    async def hybrid_ping(self, url: str) -> float:
        """混合测速：优先使用 Rust 实现"""
        if cached := self._get_cached(url):
            return cached
        
        host = url.split("//")[-1].split("/")[0]
        if self.rust_enabled:
            latency = await rs_async_ping(host, 80)
        else:
            latency = await self.py_ping(host)  # 原有 Python 实现
        
        self._update_cache(url, latency)
        return latency
    
    @staticmethod
    async def py_ping(host: str) -> float:
        # 原有 Python 实现（略）
    
    def _get_cached(self, url: str) -> Optional[float]:
        entry = self._CACHE.get(url)
        if entry and time.time() - entry['time'] < self.MAX_CACHE_AGE:
            return entry['latency']
        return None
    
    def _update_cache(self, url: str, latency: float):
        self._CACHE[url] = {'time': time.time(), 'latency': latency}